package com.zklh.leetcode.interviewTop150;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 简化路径 实现
 */
public class Solution71 {
    public String simplifyPath(String path) {
        Deque<String> stack = new LinkedList<>();
        int current = 0;
        while (current < path.length()) {
            if ('/' == path.charAt(current)) {
                current ++;
                continue;
            }
            int start = current;
            while (current < path.length() && '/' != path.charAt(current)) {
                current++;
            }
            if ("..".equals(path.substring(start, current))) {
                stack.poll();
            } else {
                stack.push(path.substring(start, current));
            }
        }
        if(stack.isEmpty()) {
            return "/";
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.append("/").append(stack.pollLast());
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Solution71 solution71 = new Solution71();
        System.out.println(solution71.simplifyPath("/a/./b/../../c/"));
        System.out.println(solution71.simplifyPath("/home//foo/"));
    }
}
